import 'package:flutter/material.dart';
import 'dart:io';
import '../data/user_data.dart';
import '../utils/responsive_util.dart';
import '../services/auth_service.dart';
import '../services/student_service.dart';
import '../services/file_select_service.dart';
import '../services/exam_service.dart';
import 'package:url_launcher/url_launcher.dart';
// Commented out temporarily
// import 'package:file_picker/file_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:excel/excel.dart' hide Border;
import 'package:permission_handler/permission_handler.dart';
// Use Flutter's Border explicitly when needed
import 'package:flutter/material.dart' show Border, BorderSide;
import 'package:flutter/services.dart';
import 'dart:async'; // 导入Timer

class LoginScreen extends StatefulWidget {
  const LoginScreen({super.key});

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> with WidgetsBindingObserver {
  final _formKey = GlobalKey<FormState>();
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();
  bool _isLoading = false;
  String? _errorMessage;
  
  // 管理员自动登出相关变量
  Timer? _inactivityTimer;
  static const int _adminInactivityTimeout = 60; // 60秒无操作自动登出
  int _remainingSeconds = _adminInactivityTimeout;
  bool _showCountdown = false;
  bool _isAdminLoggedIn = false;

  @override
  void initState() {
    super.initState();
    // 注册应用状态观察者
    WidgetsBinding.instance.addObserver(this);
    // 初始化学生服务
    StudentService.init();
    // 初始化考试服务
    ExamService.init();

    // 设置默认测试用户名，方便测试
    _usernameController.text = "申今琼";
    _passwordController.text = "610122197909046158";
    
    // 确保Excel目录存在
    _ensureExcelDirectoryExists();
  }

  @override
  void dispose() {
    // 移除应用状态观察者
    WidgetsBinding.instance.removeObserver(this);
    // 取消定时器
    _inactivityTimer?.cancel();
    _usernameController.dispose();
    _passwordController.dispose();
    super.dispose();
  }
  
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // 管理员不需要自动退出逻辑，只有学生需要
    // 注释掉管理员的应用状态变化处理
    // if (_isAdminLoggedIn) {
    //   if (state == AppLifecycleState.resumed) {
    //     _startInactivityTimer();
    //   } else if (state == AppLifecycleState.paused) {
    //     _inactivityTimer?.cancel();
    //   }
    // }
  }
  
  // 学生用户无操作退出计时器（管理员不使用）
  void _startInactivityTimer() {
    // 管理员不启动自动退出计时器
    return;
    
    // 以下代码保留但不执行，仅供参考
    // // 取消可能存在的定时器
    // _inactivityTimer?.cancel();
    // 
    // // 重置倒计时秒数
    // _remainingSeconds = _adminInactivityTimeout;
    // 
    // if (_isAdminLoggedIn) {
    //   _inactivityTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
    //     setState(() {
    //       if (_remainingSeconds > 0) {
    //         _remainingSeconds--;
    //         
    //         // 最后10秒显示倒计时
    //         if (_remainingSeconds <= 10 && !_showCountdown) {
    //           _showCountdown = true;
    //         }
    //       } else {
    //         // 时间到，自动登出
    //         _inactivityTimer?.cancel();
    //         _autoLogout();
    //       }
    //     });
    //   });
    // }
  }
  
  // 用户交互时重置定时器（管理员不使用）
  void _resetInactivityTimer() {
    // 管理员不需要自动退出计时器
    return;
    
    // 以下代码保留但不执行
    // if (_isAdminLoggedIn) {
    //   setState(() {
    //     _showCountdown = false;
    //   });
    //   _startInactivityTimer();
    // }
  }
  
  // 自动登出操作（管理员不使用）
  void _autoLogout() {
    // 管理员不自动登出
    return;
    
    // 以下代码保留但不执行
    // if (_isAdminLoggedIn) {
    //   // 注销登录
    //   UserData.logout();
    //   
    //   setState(() {
    //     _isAdminLoggedIn = false;
    //     _showCountdown = false;
    //   });
    //   
    //   // 显示消息
    //   ScaffoldMessenger.of(context).showSnackBar(
    //     const SnackBar(content: Text('由于长时间无操作，管理员已被自动登出'))
    //   );
    // }
  }

  void _login() {
    if (_formKey.currentState!.validate()) {
      setState(() {
        _isLoading = true;
        _errorMessage = null;
      });

      // 尝试登录
      final username = _usernameController.text.trim();
      final password = _passwordController.text.trim();
      
      // 模拟网络延迟
      Future.delayed(const Duration(seconds: 1), () async {
        // 使用新的登录方法
        final loginSuccess = await AuthService.login(username, password);
        
        setState(() {
          _isLoading = false;
        });

        if (loginSuccess) {
          // 检查是否是管理员登录
          final isAdmin = UserData.isAdminUser;
          
          // 确保在导航前设置好状态
          setState(() {
            _isAdminLoggedIn = isAdmin;
          });
          
          // 登录成功，导航到首页
          Navigator.pushReplacementNamed(context, '/home');
        } else {
          // 登录失败，显示错误信息
          setState(() {
            _errorMessage = '用户名或密码错误，请重试！';
          });
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    // 固定尺寸，为1080x1920优化
    final bool isTablet = ResponsiveUtil.isTablet(context);
    final double borderRadius = ResponsiveUtil.getBorderRadius(context, base: 25.0);
    final double standardSpacing = ResponsiveUtil.scaleWidth(context, 16.0);
    final double standardPadding = ResponsiveUtil.scaleWidth(context, 24.0);
    
    return Listener(
      // 监听所有触摸事件，重置无操作计时器
      onPointerDown: (_) => _resetInactivityTimer(),
      onPointerMove: (_) => _resetInactivityTimer(),
      onPointerUp: (_) => _resetInactivityTimer(),
      child: Scaffold(
        body: Stack(
          children: [
            Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [
                    Colors.blue.shade900,
                    Colors.blue.shade800,
                    Colors.blue.shade400,
                  ],
                ),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(height: ResponsiveUtil.scaleHeight(context, 80.0)),
                  Padding(
                    padding: EdgeInsets.all(standardSpacing),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              "登录",
                              style: ResponsiveUtil.getBalancedTextStyle(
                                context,
                                fontSize: 40.0,
                                fontWeight: FontWeight.bold,
                                color: Colors.white,
                              ),
                            ),
                            SizedBox(height: ResponsiveUtil.scaleHeight(context, 10.0)),
                            Text(
                              "欢迎回来",
                              style: ResponsiveUtil.getBalancedTextStyle(
                                context,
                                fontSize: 18.0,
                                color: Colors.white.withOpacity(0.9),
                              ),
                            ),
                          ],
                        ),
                        // 添加管理员按钮
                        IconButton(
                          icon: Icon(
                            Icons.admin_panel_settings,
                            color: Colors.white,
                            size: ResponsiveUtil.getIconSize(context, base: 30),
                          ),
                          onPressed: () {
                            _resetInactivityTimer();
                            _showAdminDialog();
                          },
                          tooltip: '管理员功能',
                        ),
                      ],
                    ),
                  ),
                  SizedBox(height: 20.0),
                  Expanded(
                    child: Container(
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(borderRadius),
                          topRight: Radius.circular(borderRadius),
                        ),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.1),
                            blurRadius: 10,
                            offset: const Offset(0, -4),
                          ),
                        ],
                      ),
                      child: SingleChildScrollView(
                        child: Padding(
                          padding: EdgeInsets.all(standardPadding),
                          child: Column(
                            children: [
                              SizedBox(height: 60.0),
                              Container(
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(12.0),
                                  boxShadow: [
                                    BoxShadow(
                                      color: Colors.blue.withOpacity(0.3),
                                      blurRadius: 20,
                                      offset: const Offset(0, 10),
                                    ),
                                  ],
                                ),
                                child: Form(
                                  key: _formKey,
                                  child: Column(
                                    children: [
                                      Container(
                                        padding: EdgeInsets.all(standardSpacing * 0.5),
                                        decoration: BoxDecoration(
                                          border: Border(
                                            bottom: BorderSide(color: Colors.grey.shade200),
                                          ),
                                        ),
                                        child: TextFormField(
                                          controller: _usernameController,
                                          style: TextStyle(
                                            fontSize: 16.0,
                                            color: Colors.grey.shade700,
                                          ),
                                          decoration: InputDecoration(
                                            hintText: "姓名",
                                            hintStyle: TextStyle(color: Colors.grey),
                                            contentPadding: EdgeInsets.symmetric(
                                              vertical: 12.0,
                                              horizontal: 10.0,
                                            ),
                                            border: InputBorder.none,
                                          ),
                                          validator: (value) {
                                            if (value == null || value.isEmpty) {
                                              return '请输入姓名';
                                            }
                                            return null;
                                          },
                                          onTap: _resetInactivityTimer,
                                          onChanged: (_) => _resetInactivityTimer(),
                                        ),
                                      ),
                                      Container(
                                        padding: EdgeInsets.all(standardSpacing * 0.5),
                                        child: TextFormField(
                                          controller: _passwordController,
                                          obscureText: true,
                                          style: TextStyle(
                                            fontSize: 16.0,
                                            color: Colors.grey.shade700,
                                          ),
                                          decoration: InputDecoration(
                                            hintText: "身份证号码",
                                            hintStyle: TextStyle(color: Colors.grey),
                                            contentPadding: EdgeInsets.symmetric(
                                              vertical: 12.0,
                                              horizontal: 10.0,
                                            ),
                                            border: InputBorder.none,
                                          ),
                                          validator: (value) {
                                            if (value == null || value.isEmpty) {
                                              return '请输入身份证号码';
                                            }
                                            // 简单校验身份证号长度
                                            if (value.length < 15) {
                                              return '身份证号码格式不正确';
                                            }
                                            return null;
                                          },
                                          onTap: _resetInactivityTimer,
                                          onChanged: (_) => _resetInactivityTimer(),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                              SizedBox(height: 20.0),
                              // 错误信息显示
                              if (_errorMessage != null)
                                Container(
                                  width: double.infinity,
                                  padding: EdgeInsets.all(standardSpacing * 0.6),
                                  decoration: BoxDecoration(
                                    color: Colors.red.shade50,
                                    borderRadius: BorderRadius.circular(8.0),
                                    border: Border.all(color: Colors.red.shade200),
                                  ),
                                  child: Text(
                                    _errorMessage!,
                                    style: TextStyle(
                                      fontSize: 14.0,
                                      color: Colors.red.shade800,
                                    ),
                                    textAlign: TextAlign.center,
                                  ),
                                ),
                              SizedBox(height: 20.0),
                              Text(
                                "忘记密码?",
                                style: TextStyle(
                                  fontSize: 14.0,
                                  color: Colors.grey,
                                ),
                              ),
                              SizedBox(height: 40.0),
                              SizedBox(
                                width: double.infinity,
                                height: 50.0,
                                child: ElevatedButton(
                                  onPressed: _isLoading ? null : _login,
                                  style: ElevatedButton.styleFrom(
                                    backgroundColor: Colors.blue.shade900,
                                    foregroundColor: Colors.white,
                                    padding: EdgeInsets.symmetric(
                                      vertical: 12.0,
                                      horizontal: 24.0,
                                    ),
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(25.0),
                                    ),
                                    textStyle: TextStyle(
                                      fontSize: 16.0,
                                      fontWeight: FontWeight.bold,
                                      color: Colors.white,
                                    ),
                                  ),
                                  child: _isLoading
                                      ? SizedBox(
                                          width: 24.0,
                                          height: 24.0,
                                          child: CircularProgressIndicator(
                                            color: Colors.white,
                                            strokeWidth: 3,
                                          ),
                                        )
                                      : Text(
                                          "登录",
                                          style: TextStyle(
                                            fontSize: 16.0,
                                            fontWeight: FontWeight.bold,
                                            color: Colors.white,
                                            overflow: TextOverflow.visible,
                                          ),
                                        ),
                                ),
                              ),
                              SizedBox(height: 30.0),
                              Text(
                                "新用户? 联系管理员注册账号",
                                style: TextStyle(
                                  fontSize: 14.0,
                                  color: Colors.grey,
                                ),
                              ),
                              SizedBox(height: 16.0),
                              // 管理员登录按钮
                              SizedBox(
                                width: double.infinity,
                                child: OutlinedButton.icon(
                                  icon: Icon(Icons.admin_panel_settings, color: Colors.blue.shade900),
                                  label: Text(
                                    "管理员登录",
                                    style: TextStyle(
                                      color: Colors.blue.shade900,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                  style: OutlinedButton.styleFrom(
                                    side: BorderSide(color: Colors.blue.shade900),
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(25.0),
                                    ),
                                    padding: EdgeInsets.symmetric(vertical: 12.0),
                                  ),
                                  onPressed: () {
                                    _resetInactivityTimer();
                                    _showAdminLoginDialog();
                                  },
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            
            // 显示管理员倒计时（最后10秒显示）
            if (_isAdminLoggedIn && _showCountdown)
              Positioned(
                top: 16,
                right: 16,
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                  decoration: BoxDecoration(
                    color: _remainingSeconds <= 5 ? Colors.red.shade700 : Colors.orange.shade700,
                    borderRadius: BorderRadius.circular(20),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black26,
                        blurRadius: 6,
                        offset: Offset(0, 2),
                      ),
                    ],
                  ),
                  child: Row(
                    children: [
                      Icon(Icons.timer, size: 16, color: Colors.white),
                      SizedBox(width: 4),
                      Text(
                        "$_remainingSeconds秒后登出",
                        style: TextStyle(
                          fontSize: 12,
                          fontWeight: FontWeight.bold,
                          color: Colors.white,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            
            // 悬浮关闭按钮
            Positioned(
              top: 16,
              right: _isAdminLoggedIn && _showCountdown ? 120 : 16, // 根据是否显示倒计时调整位置
              child: Material(
                color: Colors.transparent,
                child: InkWell(
                  onTap: () {
                    _resetInactivityTimer();
                    _showCloseAppDialog();
                  },
                  borderRadius: BorderRadius.circular(20),
                  child: Container(
                    padding: EdgeInsets.all(8),
                    decoration: BoxDecoration(
                      color: Colors.red.withOpacity(0.85),
                      shape: BoxShape.circle,
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black26,
                          blurRadius: 6,
                          offset: Offset(0, 2),
                        ),
                      ],
                    ),
                    child: Icon(
                      Icons.power_settings_new,
                      color: Colors.white,
                      size: 24,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  // 显示管理员功能对话框
  void _showAdminDialog() {
    // 重置管理员无操作计时器
    _resetInactivityTimer();
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(
          '管理员功能',
          style: ResponsiveUtil.getBalancedTextStyle(
            context,
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: Icon(Icons.person_add, color: Colors.blue),
              title: Text('添加学生'),
              subtitle: Text('手动添加学生信息'),
              onTap: () {
                Navigator.pop(context);
                _showAddStudentDialog();
              },
            ),
            ListTile(
              leading: Icon(Icons.file_upload, color: Colors.teal),
              title: Text('Excel导入学生'),
              subtitle: Text('从Excel文件导入学生信息'),
              onTap: () {
                Navigator.pop(context);
                _showExcelImportDialog(context);
              },
            ),
            ListTile(
              leading: Icon(Icons.group_add, color: Colors.green),
              title: Text('添加示例学生'),
              subtitle: Text('快速添加测试用学生数据'),
              onTap: () {
                Navigator.pop(context);
                _addSampleStudents();
              },
            ),
            ListTile(
              leading: Icon(Icons.people, color: Colors.orange),
              title: Text('学生列表'),
              subtitle: Text('查看已添加的学生列表'),
              onTap: () {
                Navigator.pop(context);
                _showStudentList();
              },
            ),
            Divider(),
            ListTile(
              leading: Icon(Icons.quiz, color: Colors.purple),
              title: Text('导入考试题目'),
              subtitle: Text('从Excel文件导入考试题目'),
              onTap: () {
                Navigator.pop(context);
                _showExamImportDialog(context);
              },
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text('关闭'),
          ),
        ],
      ),
    );
  }

  // 显示添加学生对话框
  Future<void> _showAddStudentDialog() async {
    // 请求管理员密码
    final isAdmin = await _verifyAdminPassword();
    if (!isAdmin) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('管理员验证失败，无法添加学生'))
      );
      return;
    }
    
    final nameController = TextEditingController();
    final idController = TextEditingController();
    final idCardController = TextEditingController();
    final confirmIdCardController = TextEditingController();  // 新增确认身份证输入框
    
    // 用于控制错误消息显示
    bool idCardMismatch = false;
    
    showDialog(
      context: context,
      builder: (dialogContext) => StatefulBuilder(  // 使用StatefulBuilder允许对话框内部状态更新
        builder: (context, setState) {
          return AlertDialog(
            title: Text('添加学生'),
            content: Container(
              width: double.maxFinite,
              child: SingleChildScrollView(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    TextField(
                      controller: nameController,
                      decoration: InputDecoration(
                        labelText: '姓名',
                        hintText: '请输入学生姓名',
                        border: OutlineInputBorder(),
                      ),
                    ),
                    SizedBox(height: 16),
                    TextField(
                      controller: idController,
                      decoration: InputDecoration(
                        labelText: '账号',
                        hintText: '请输入学生账号',
                        border: OutlineInputBorder(),
                      ),
                    ),
                    SizedBox(height: 16),
                    TextField(
                      controller: idCardController,
                      decoration: InputDecoration(
                        labelText: '身份证号码',
                        hintText: '请输入学生身份证号码',
                        border: OutlineInputBorder(),
                        errorText: idCardMismatch ? null : null,  // 通过其他方式显示错误
                      ),
                      onChanged: (_) {
                        // 当输入变化时，重置不匹配状态
                        if (idCardMismatch) {
                          setState(() {
                            idCardMismatch = false;
                          });
                        }
                      },
                    ),
                    SizedBox(height: 16),
                    TextField(
                      controller: confirmIdCardController,
                      decoration: InputDecoration(
                        labelText: '确认身份证号码',
                        hintText: '请再次输入学生身份证号码',
                        border: OutlineInputBorder(),
                        errorText: idCardMismatch ? '两次输入的身份证号码不一致' : null,
                      ),
                      onChanged: (_) {
                        // 当输入变化时，重置不匹配状态
                        if (idCardMismatch) {
                          setState(() {
                            idCardMismatch = false;
                          });
                        }
                      },
                    ),
                    if (idCardMismatch)
                      Padding(
                        padding: const EdgeInsets.only(top: 8.0),
                        child: Text(
                          '两次输入的身份证号码不一致，请检查',
                          style: TextStyle(color: Colors.red, fontSize: 12),
                        ),
                      ),
                  ],
                ),
              ),
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: Text('取消'),
              ),
              TextButton(
                onPressed: () async {
                  // 验证两次输入的身份证号码是否一致
                  if (idCardController.text != confirmIdCardController.text) {
                    setState(() {
                      idCardMismatch = true;
                    });
                    return;
                  }
                  
                  // 添加学生
                  final result = await StudentService.addStudent(
                    nameController.text.trim(), 
                    idController.text.trim(), 
                    idCardController.text.trim()
                  );
                  
                  Navigator.pop(context);
                  
                  // 显示结果
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(
                      content: Text(result.message),
                      backgroundColor: result.success ? Colors.green : Colors.red,
                    )
                  );
                  
                  // 如果成功，显示学生列表
                  if (result.success) {
                    _showStudentList();
                  }
                },
                child: Text('添加'),
              ),
            ],
          );
        }
      ),
    );
  }
  
  // 添加示例学生
  Future<void> _addSampleStudents() async {
    // 请求管理员密码
    final isAdmin = await _verifyAdminPassword();
    if (!isAdmin) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('管理员验证失败，无法添加示例学生'))
      );
      return;
    }
    
    // 显示确认对话框
    bool? confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('添加示例学生'),
        content: Text('这将添加3名示例学生数据（张三、李四、王五）。确定要继续吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: Text('确定'),
          ),
        ],
      ),
    );
    
    if (confirmed != true) {
      return;
    }
    
    // 显示加载对话框
    _showLoadingDialog('正在添加示例学生...');
    
    // 添加示例学生
    final result = await StudentService.addSampleStudents();
    
    // 关闭加载对话框
    Navigator.pop(context);
    
    // 显示结果
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(result.message),
        backgroundColor: result.success ? Colors.green : Colors.red,
      )
    );
    
    // 如果成功，显示学生列表
    if (result.success) {
      _showStudentList();
    }
  }
  
  // 显示学生列表
  void _showStudentList() async {
    // 请求管理员密码
    final isAdmin = await _verifyAdminPassword();
    if (!isAdmin) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('管理员验证失败，无法查看学生列表'))
      );
      return;
    }
    
    final students = StudentService.getStudents();
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('已导入的学生'),
        content: Container(
          width: double.maxFinite,
          child: students.isEmpty
            ? Center(
                child: Padding(
                  padding: const EdgeInsets.all(20.0),
                  child: Text('没有导入的学生数据'),
                ),
              )
            : ListView.builder(
                shrinkWrap: true,
                itemCount: students.length,
                itemBuilder: (context, index) {
                  final student = students[index];
                  return ListTile(
                    title: Text(student.name),
                    subtitle: Text('账号: ${student.id}'),
                    trailing: Text('身份证: ${_maskIdCard(student.idCardNumber)}'),
                  );
                },
              ),
        ),
        actions: [
          if (students.isNotEmpty)
            TextButton(
              onPressed: () {
                _showClearConfirmDialog();
              },
              child: Text('清空数据', style: TextStyle(color: Colors.red)),
            ),
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text('关闭'),
          ),
        ],
      ),
    );
  }
  
  // 显示清空确认对话框
  void _showClearConfirmDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('确认清空'),
        content: Text('确定要清空所有学生数据吗？此操作不可恢复。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              Navigator.pop(context); // 关闭确认对话框
              
              // 请求管理员密码
              final isAdmin = await _verifyAdminPassword();
              if (!isAdmin) {
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('管理员验证失败，无法清空数据'))
                );
                return;
              }
              
              // 清空数据
              final cleared = await StudentService.clearAllStudents();
              
              if (cleared) {
                // 关闭学生列表对话框
                Navigator.pop(context);
                
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('学生数据已清空'))
                );
              } else {
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('清空数据失败'))
                );
              }
            },
            child: Text('确认清空', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );
  }
  
  // 验证管理员密码
  Future<bool> _verifyAdminPassword() async {
    final TextEditingController passwordController = TextEditingController();
    bool? result;
    
    await showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('管理员验证'),
        content: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                '请输入管理员密码以继续操作',
                style: TextStyle(fontSize: 14),
              ),
              SizedBox(height: 12),
              TextField(
                controller: passwordController,
                obscureText: true,
                decoration: InputDecoration(
                  hintText: '管理员密码',
                  border: OutlineInputBorder(),
                  contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                ),
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () {
              result = false;
              Navigator.pop(context);
            },
            child: Text('取消'),
          ),
          TextButton(
            onPressed: () {
              // 使用统一的管理员密码验证
              result = UserData.verifyAdminPassword(passwordController.text);
              Navigator.pop(context);
            },
            child: Text('确认'),
          ),
        ],
      ),
    );
    
    return result ?? false;
  }
  
  // 显示加载对话框
  void _showLoadingDialog(String message) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        content: Row(
          children: [
            CircularProgressIndicator(),
            SizedBox(width: 20),
            Text(message),
          ],
        ),
      ),
    );
  }
  
  // 遮蔽身份证号码，只显示前四位和后四位
  String _maskIdCard(String idCard) {
    if (idCard.length < 8) return idCard;
    return idCard.substring(0, 4) + '********' + idCard.substring(idCard.length - 4);
  }

  // 显示Excel导入对话框
  void _showExcelImportDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('导入学生信息', style: TextStyle(
            fontSize: ResponsiveUtil.isTablet(context) ? 22 : 18,
            fontWeight: FontWeight.bold,
          )),
          content: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('Excel文件要求：', style: TextStyle(
                  fontSize: ResponsiveUtil.isTablet(context) ? 16 : 14,
                  fontWeight: FontWeight.w500,
                )),
                SizedBox(height: 8),
                _buildInfoItem('• 第一行必须包含列标题："姓名"、"账号"和"身份证号码"'),
                _buildInfoItem('• 从第二行开始填写学生信息数据'),
                _buildInfoItem('• 支持.xlsx格式的Excel文件'),
                _buildInfoItem('• 每个学生账号不能重复'),
                
                SizedBox(height: 12),
                Text('操作说明：', style: TextStyle(
                  fontSize: ResponsiveUtil.isTablet(context) ? 16 : 14,
                  fontWeight: FontWeight.w500,
                )),
                SizedBox(height: 8),
                _buildInfoItem('1. 准备好符合上述要求的Excel文件'),
                _buildInfoItem('2. 将Excel文件保存到手机存储的ExamApp文件夹'),
                _buildInfoItem('3. 点击下方"导入Excel文件"按钮'),
                _buildInfoItem('4. 从列表中选择要导入的文件'),
                _buildInfoItem('5. 系统会自动验证和导入学生数据'),
                
                SizedBox(height: 20),
                Text('遇到导入问题？', 
                  style: TextStyle(
                    fontSize: ResponsiveUtil.isTablet(context) ? 16 : 14,
                    fontWeight: FontWeight.w500,
                    color: Colors.red
                  )
                ),
                _buildInfoItem('• 如果文件损坏或格式不正确，可以尝试使用下方的按钮创建模板文件'),
                _buildInfoItem('• 在模板文件中填入学生信息后再导入'),
                
                SizedBox(height: 20),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    ElevatedButton.icon(
                      icon: Icon(Icons.file_download, 
                        size: ResponsiveUtil.isTablet(context) ? 24 : 20),
                      label: Text('创建模板', style: TextStyle(
                        fontSize: ResponsiveUtil.isTablet(context) ? 16 : 14,
                      )),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.green,
                        padding: EdgeInsets.symmetric(
                          horizontal: ResponsiveUtil.isTablet(context) ? 20 : 12, 
                          vertical: ResponsiveUtil.isTablet(context) ? 12 : 8
                        ),
                      ),
                      onPressed: () => _generateExcelTemplate(context),
                    ),
                    ElevatedButton.icon(
                      icon: Icon(Icons.file_upload, 
                        size: ResponsiveUtil.isTablet(context) ? 24 : 20),
                      label: Text('导入Excel文件', style: TextStyle(
                        fontSize: ResponsiveUtil.isTablet(context) ? 16 : 14,
                      )),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.blue,
                        padding: EdgeInsets.symmetric(
                          horizontal: ResponsiveUtil.isTablet(context) ? 24 : 16, 
                          vertical: ResponsiveUtil.isTablet(context) ? 12 : 8
                        ),
                      ),
                      onPressed: () => _importExcelFile(context),
                    ),
                  ],
                ),
              ],
            ),
          ),
          actions: [
            TextButton(
              child: Text('关闭', style: TextStyle(
                fontSize: ResponsiveUtil.isTablet(context) ? 16 : 14,
              )),
              onPressed: () => Navigator.of(context).pop(),
            ),
          ],
        );
      },
    );
  }
  
  // 生成Excel模板
  Future<void> _generateExcelTemplate(BuildContext context) async {
    try {
      // 请求存储权限
      final status = await Permission.storage.request();
      if (!status.isGranted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('需要存储权限来创建Excel模板文件'))
        );
        return;
      }
      
      // 显示加载对话框
      _showLoadingDialog('正在创建Excel模板...');
      
      // 生成模板
      final templatePath = await StudentService.generateTemplateToExternal();
      
      // 关闭加载对话框
      Navigator.of(context).pop();
      
      if (templatePath != null) {
        final file = File(templatePath);
        final directory = file.parent.path;
        final fileName = file.path.split('/').last;
        
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: Text('模板创建成功'),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('模板文件已保存到:'),
                SizedBox(height: 8),
                Container(
                  padding: EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: Colors.grey.shade200,
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '文件夹: ${directory}',
                        style: TextStyle(fontFamily: 'monospace', fontSize: 12),
                      ),
                      SizedBox(height: 4),
                      Text(
                        '文件名: ${fileName}',
                        style: TextStyle(fontFamily: 'monospace', fontSize: 12),
                      ),
                    ],
                  ),
                ),
                SizedBox(height: 16),
                Text('请使用电子表格应用打开此文件，填入学生信息后保存。'),
                SizedBox(height: 12),
                Text('提示：在Android手机上，可以在"文件管理"应用中的"下载"文件夹中找到ExamApp目录。', 
                  style: TextStyle(
                    color: Colors.blue.shade700,
                    fontSize: 13,
                    fontStyle: FontStyle.italic,
                  ),
                ),
              ],
            ),
            actions: [
              if (Platform.isAndroid)
                TextButton.icon(
                  icon: Icon(Icons.folder_open),
                  label: Text('打开文件夹'),
                  onPressed: () async {
                    Navigator.pop(context);
                    
                    try {
                      // 尝试打开文件夹
                      final url = 'content://com.android.externalstorage.documents/document/primary%3ADownload%2FExamApp';
                      final canOpen = await canLaunchUrl(Uri.parse(url));
                      if (canOpen) {
                        await launchUrl(Uri.parse(url));
                      } else {
                        // 如果直接打开失败，尝试使用其他方式
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(content: Text('无法直接打开文件夹，请使用文件管理器手动查找'))
                        );
                      }
                    } catch (e) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(content: Text('打开文件夹失败: ${e.toString()}'))
                      );
                    }
                  },
                ),
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: Text('确定'),
              ),
            ],
          ),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('创建模板失败，请确保应用有足够的存储权限'))
        );
      }
    } catch (e) {
      // 关闭可能存在的加载对话框
      Navigator.of(context).pop();
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('创建模板时发生错误: ${e.toString()}'))
      );
    }
  }

  // 构建信息项
  Widget _buildInfoItem(String text) {
    return Padding(
      padding: EdgeInsets.only(bottom: 6),
      child: Text(
        text,
        style: TextStyle(
          fontSize: ResponsiveUtil.isTablet(context) ? 15 : 13,
          color: Colors.black87,
        ),
      ),
    );
  }

  // 显示导入结果对话框
  void _showResultDialog(BuildContext context, ImportResult result) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(
            result.success ? '导入成功' : '导入失败',
            style: TextStyle(
              color: result.success ? Colors.green : Colors.red,
              fontSize: ResponsiveUtil.isTablet(context) ? 22 : 18,
            ),
          ),
          content: SingleChildScrollView(
            child: Text(
              result.message,
              style: TextStyle(
                fontSize: ResponsiveUtil.isTablet(context) ? 16 : 14,
              ),
            ),
          ),
          actions: [
            TextButton(
              child: Text(
                '确定',
                style: TextStyle(
                  fontSize: ResponsiveUtil.isTablet(context) ? 16 : 14,
                ),
              ),
              onPressed: () => Navigator.of(context).pop(),
            ),
          ],
        );
      },
    );
  }

  // 导入Excel文件
  Future<void> _importExcelFile(BuildContext context) async {
    try {
      // 请求存储权限
      final status = await Permission.storage.request();
      if (!status.isGranted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('需要存储权限来访问Excel文件'))
        );
        return;
      }
      
      // 让用户选择Excel文件
      File? selectedFile = await FileSelectService.pickExcelFile();
      
      if (selectedFile == null) {
        // 用户取消了选择
        return;
      }
      
      // 获取文件名并设置为默认标题
      String fileName = selectedFile.path.split('/').last;
      // 去掉文件扩展名，仅使用文件名作为标题和描述
      String fileNameWithoutExt = fileName.contains('.') 
          ? fileName.substring(0, fileName.lastIndexOf('.')) 
          : fileName;
      
      // 显示确认对话框
      final examTitle = TextEditingController(text: fileNameWithoutExt);
      final examDescription = TextEditingController(text: fileNameWithoutExt);
      final examDuration = TextEditingController(text: '60');
      
      bool? confirmed = await showDialog<bool>(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text('确认导入'),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('确认从以下文件导入学生数据：'),
                SizedBox(height: 8),
                Container(
                  padding: EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: Colors.grey.shade200,
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: Text(
                    selectedFile.path.split('/').last,
                    style: TextStyle(fontFamily: 'monospace'),
                  ),
                ),
              ],
            ),
            actions: [
              TextButton(
                child: Text('取消'),
                onPressed: () => Navigator.of(context).pop(false),
              ),
              TextButton(
                child: Text('确认导入'),
                onPressed: () => Navigator.of(context).pop(true),
              ),
            ],
          );
        },
      );
      
      if (confirmed != true) {
        return;
      }
      
      // 显示加载对话框
      _showLoadingDialog('正在导入学生数据...');
      
      // 导入Excel数据
      final importResult = await StudentService.importFromExcel(selectedFile);
      
      // 关闭加载对话框
      Navigator.of(context).pop();
      
      // 显示结果
      _showResultDialog(context, importResult);
    } catch (e) {
      // 处理可能的错误
      _showResultDialog(
        context, 
        ImportResult(
          success: false, 
          message: '文件导入过程中发生错误: ${e.toString()}',
        ),
      );
    }
  }

  // 确保Excel目录存在
  Future<void> _ensureExcelDirectoryExists() async {
    try {
      await StudentService.ensureExcelDirectoryExists();
    } catch (e) {
      debugPrint('确保Excel目录存在失败: $e');
    }
  }
  
  // 显示考试题目导入对话框
  void _showExamImportDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('导入考试题目', style: TextStyle(
            fontSize: ResponsiveUtil.isTablet(context) ? 22 : 18,
            fontWeight: FontWeight.bold,
          )),
          content: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('Excel文件要求：', style: TextStyle(
                  fontSize: ResponsiveUtil.isTablet(context) ? 16 : 14,
                  fontWeight: FontWeight.w500,
                )),
                SizedBox(height: 8),
                _buildInfoItem('• 第一行必须包含列标题："题目id"、"题目名称"、"题目类型"、"知识点"、"题目难度"、"题目选项"、"题目答案"和"答案分析"'),
                _buildInfoItem('• "题目类型"可用值：单选、多选、填空、判断、简答'),
                _buildInfoItem('• "题目难度"可用值：基础、中等、困难，不同难度对应不同分值'),
                _buildInfoItem('• 单选和多选题需要在"题目选项"列中使用JSON格式指定选项'),
                _buildInfoItem('• 支持.xlsx格式的Excel文件'),
                
                SizedBox(height: 12),
                Text('操作说明：', style: TextStyle(
                  fontSize: ResponsiveUtil.isTablet(context) ? 16 : 14,
                  fontWeight: FontWeight.w500,
                )),
                SizedBox(height: 8),
                _buildInfoItem('1. 准备好符合上述要求的Excel文件'),
                _buildInfoItem('2. 将Excel文件保存到手机存储的ExamApp文件夹'),
                _buildInfoItem('3. 点击下方"导入Excel文件"按钮'),
                _buildInfoItem('4. 从列表中选择要导入的文件'),
                _buildInfoItem('5. 系统会自动验证和导入题目数据'),
                
                SizedBox(height: 20),
                Text('遇到导入问题？', 
                  style: TextStyle(
                    fontSize: ResponsiveUtil.isTablet(context) ? 16 : 14,
                    fontWeight: FontWeight.w500,
                    color: Colors.red
                  )
                ),
                _buildInfoItem('• 如果文件损坏或格式不正确，可以尝试使用下方的按钮创建模板文件'),
                _buildInfoItem('• 在模板文件中填入题目信息后再导入'),
                
                SizedBox(height: 20),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    ElevatedButton.icon(
                      icon: Icon(Icons.file_download, 
                        size: ResponsiveUtil.isTablet(context) ? 24 : 20),
                      label: Text('创建模板', style: TextStyle(
                        fontSize: ResponsiveUtil.isTablet(context) ? 16 : 14,
                      )),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.green,
                        padding: EdgeInsets.symmetric(
                          horizontal: ResponsiveUtil.isTablet(context) ? 20 : 12, 
                          vertical: ResponsiveUtil.isTablet(context) ? 12 : 8
                        ),
                      ),
                      onPressed: () => _generateExamTemplate(context),
                    ),
                    ElevatedButton.icon(
                      icon: Icon(Icons.file_upload, 
                        size: ResponsiveUtil.isTablet(context) ? 24 : 20),
                      label: Text('导入Excel文件', style: TextStyle(
                        fontSize: ResponsiveUtil.isTablet(context) ? 16 : 14,
                      )),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.blue,
                        padding: EdgeInsets.symmetric(
                          horizontal: ResponsiveUtil.isTablet(context) ? 24 : 16, 
                          vertical: ResponsiveUtil.isTablet(context) ? 12 : 8
                        ),
                      ),
                      onPressed: () => _importExamFile(context),
                    ),
                  ],
                ),
              ],
            ),
          ),
          actions: [
            TextButton(
              child: Text('关闭', style: TextStyle(
                fontSize: ResponsiveUtil.isTablet(context) ? 16 : 14,
              )),
              onPressed: () => Navigator.of(context).pop(),
            ),
          ],
        );
      },
    );
  }
  
  // 生成考试题目的Excel模板
  Future<void> _generateExamTemplate(BuildContext context) async {
    try {
      // 请求存储权限
      final status = await Permission.storage.request();
      if (!status.isGranted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('需要存储权限来创建Excel模板文件'))
        );
        return;
      }
      
      // 先检查用户是否为管理员
      final isAdmin = await _verifyAdminPassword();
      if (!isAdmin) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('管理员验证失败，无法创建模板'))
        );
        return;
      }
      
      // 显示加载对话框
      _showLoadingDialog('正在创建Excel模板...');
      
      // 生成模板
      final templatePath = await ExamService.generateExamExcelTemplate();
      
      // 关闭加载对话框
      Navigator.of(context).pop();
      
      if (templatePath != null) {
        final file = File(templatePath);
        final directory = file.parent.path;
        final fileName = file.path.split('/').last;
        
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: Text('模板创建成功'),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('模板文件已保存到:'),
                SizedBox(height: 8),
                Container(
                  padding: EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: Colors.grey.shade200,
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '文件夹: $directory',
                        style: TextStyle(fontFamily: 'monospace', fontSize: 12),
                      ),
                      SizedBox(height: 4),
                      Text(
                        '文件名: $fileName',
                        style: TextStyle(fontFamily: 'monospace', fontSize: 12),
                      ),
                    ],
                  ),
                ),
                SizedBox(height: 16),
                Text('请使用电子表格应用打开此文件，填入题目数据后保存。'),
                SizedBox(height: 12),
                Text('提示：在Android手机上，可以在"文件管理"应用中的"下载"文件夹中找到ExamApp目录。', 
                  style: TextStyle(
                    color: Colors.blue.shade700,
                    fontSize: 13,
                    fontStyle: FontStyle.italic,
                  ),
                ),
              ],
            ),
            actions: [
              if (Platform.isAndroid)
                TextButton.icon(
                  icon: Icon(Icons.folder_open),
                  label: Text('打开文件夹'),
                  onPressed: () async {
                    Navigator.pop(context);
                    
                    try {
                      // 尝试打开文件夹
                      final url = 'content://com.android.externalstorage.documents/document/primary%3ADownload%2FExamApp';
                      final canOpen = await canLaunchUrl(Uri.parse(url));
                      if (canOpen) {
                        await launchUrl(Uri.parse(url));
                      } else {
                        // 如果直接打开失败，尝试使用其他方式
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(content: Text('无法直接打开文件夹，请使用文件管理器手动查找'))
                        );
                      }
                    } catch (e) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(content: Text('打开文件夹失败: ${e.toString()}'))
                      );
                    }
                  },
                ),
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: Text('确定'),
              ),
            ],
          ),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('创建模板失败，请确保应用有足够的存储权限'))
        );
      }
    } catch (e) {
      // 关闭可能存在的加载对话框
      Navigator.of(context).pop();
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('创建模板时发生错误: ${e.toString()}'))
      );
    }
  }

  // 导入考试题目Excel文件
  Future<void> _importExamFile(BuildContext context) async {
    try {
      // 请求存储权限
      final status = await Permission.storage.request();
      if (!status.isGranted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('需要存储权限来访问Excel文件'))
        );
        return;
      }
      
      // 先检查用户是否为管理员
      final isAdmin = await _verifyAdminPassword();
      if (!isAdmin) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('管理员验证失败，无法导入题目'))
        );
        return;
      }
      
      // 让用户选择Excel文件
      File? selectedFile = await FileSelectService.pickExcelFile();
      
      if (selectedFile == null) {
        // 用户取消了选择
        return;
      }
      
      // 获取文件名并设置为默认标题
      String fileName = selectedFile.path.split('/').last;
      // 去掉文件扩展名，仅使用文件名作为标题和描述
      String fileNameWithoutExt = fileName.contains('.') 
          ? fileName.substring(0, fileName.lastIndexOf('.')) 
          : fileName;
      
      // 显示确认对话框
      final examTitle = TextEditingController(text: fileNameWithoutExt);
      final examDescription = TextEditingController(text: fileNameWithoutExt);
      final examDuration = TextEditingController(text: '60');
      
      bool? confirmed = await showDialog<bool>(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text('确认导入'),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('选择的文件:'),
                SizedBox(height: 8),
                Container(
                  padding: EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: Colors.grey.shade200,
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: Text(
                    selectedFile.path.split('/').last,
                    style: TextStyle(fontFamily: 'monospace'),
                  ),
                ),
                SizedBox(height: 16),
                Text('请设置考试信息:'),
                SizedBox(height: 12),
                TextField(
                  controller: examTitle,
                  decoration: InputDecoration(
                    labelText: '考试标题',
                    border: OutlineInputBorder(),
                  ),
                ),
                SizedBox(height: 12),
                TextField(
                  controller: examDescription,
                  decoration: InputDecoration(
                    labelText: '考试描述',
                    border: OutlineInputBorder(),
                  ),
                  maxLines: 2,
                ),
                SizedBox(height: 12),
                TextField(
                  controller: examDuration,
                  decoration: InputDecoration(
                    labelText: '考试时长(分钟)',
                    border: OutlineInputBorder(),
                  ),
                  keyboardType: TextInputType.number,
                ),
              ],
            ),
            actions: [
              TextButton(
                child: Text('取消'),
                onPressed: () => Navigator.of(context).pop(false),
              ),
              TextButton(
                child: Text('确认导入'),
                onPressed: () => Navigator.of(context).pop(true),
              ),
            ],
          );
        },
      );
      
      if (confirmed != true) {
        return;
      }
      
      // 显示加载对话框
      _showLoadingDialog('正在导入考试题目...');
      
      // 导入Excel数据并创建考试
      final exam = await ExamService.createExamFromExcelFile(
        selectedFile,
        title: examTitle.text,
        description: examDescription.text,
        duration: int.tryParse(examDuration.text) ?? 60,
      );
      
      // 关闭加载对话框
      Navigator.of(context).pop();
      
      if (exam != null) {
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: Text('导入成功'),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('成功创建考试:'),
                SizedBox(height: 8),
                Text('题目: ${exam.title}'),
                Text('描述: ${exam.description}'),
                Text('时长: ${exam.duration} 分钟'),
                Text('题目数量: ${exam.questions.length}'),
                Text('总分: ${exam.totalScore}'),
              ],
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: Text('确定'),
              ),
            ],
          ),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('导入失败，请检查Excel文件格式'))
        );
      }
    } catch (e) {
      // 关闭可能存在的加载对话框
      Navigator.of(context).pop();
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('导入题目时发生错误: ${e.toString()}'))
      );
    }
  }

  // 显示管理员登录对话框
  void _showAdminLoginDialog() {
    final adminUserController = TextEditingController();
    final adminPassController = TextEditingController();
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('管理员登录'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: adminUserController,
              decoration: InputDecoration(
                labelText: '管理员账号',
                hintText: '请输入管理员账号',
              ),
            ),
            SizedBox(height: 16),
            TextField(
              controller: adminPassController,
              obscureText: true,
              decoration: InputDecoration(
                labelText: '密码',
                hintText: '请输入密码',
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              final username = adminUserController.text.trim();
              final password = adminPassController.text.trim();
              final loginSuccess = await AuthService.login(username, password);
              
              if (loginSuccess && UserData.isAdminUser) {
                Navigator.pop(context);
                
                // 设置管理员登录状态
                setState(() {
                  _isAdminLoggedIn = true;
                });
                
                // 确保登录页面向HomeScreen传递了管理员身份标志
                Navigator.pushReplacementNamed(context, '/home');
              } else {
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('管理员账号或密码错误')),
                );
              }
            },
            child: Text('登录'),
          ),
        ],
      ),
    );
  }

  void _showCloseAppDialog() {
    final TextEditingController _passwordController = TextEditingController();
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('关闭APP'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text('请输入密码以关闭APP'),
            const SizedBox(height: 16),
            TextField(
              controller: _passwordController,
              obscureText: true,
              decoration: const InputDecoration(
                labelText: '密码',
                border: OutlineInputBorder(),
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () async {
              final password = _passwordController.text.trim();
              // 使用统一的管理员密码验证
              if (UserData.verifyAdminPassword(password)) {
                Navigator.pop(context);
                await Future.delayed(const Duration(milliseconds: 200));
                SystemNavigator.pop(); // 关闭APP
              } else {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('密码错误，无法关闭APP'), backgroundColor: Colors.red),
                );
              }
            },
            child: const Text('确认关闭'),
          ),
        ],
      ),
    );
  }
} 